<!--上传组件-->
<template>
  <el-upload
    ref="uploadRef"
    class="upload-demo"
    drag
    action=""
    :auto-upload="false"
    :on-exceed="handleExceed"
    :on-change="handleChange"
    :on-remove="handleChange"
    :file-list="fileList"
    :show-file-list="false"
    :limit="1"
    :http-request="upload"
  >
    <template #trigger>
      <el-button type="primary">选择本地文件</el-button>
    </template>
    <template #default>
      <el-button class="upload" type="success" @click="uploadRef.submit()">上传</el-button>
    </template>
  </el-upload>
</template>

<script setup>
import { ref } from "vue";
import { head } from "lodash";
import { setImageUpload } from "@/api/partyBuilding";
import { ElLoading, ElMessage, genFileId } from "element-plus";
const emit = defineEmits(["setFileName"]);
const fileList = ref([]); //文件列表
const uploadRef = ref(); //上传组件实列
const loadingInstance = ref(null); // loading实例
/**
 * 自动覆盖上一个文件
 * @param files
 */
const handleExceed = files => {
  uploadRef.value.clearFiles();
  const file = head(files); //获取上传的文件,始终只有一个文件
  file.uid = genFileId();
  uploadRef.value.handleStart(file);
};
/**
 * 文件校验，当文件列表为空，附件清空
 * @param file
 * @param files
 */
const handleChange = (file, files) => {
  if (files.length) {
    emit("fileName", extractExcelBaseName(file.name));
    fileList.value.push(files.length);
  }
};
/**
 * 提取文件名
 * @param fileName
 * @returns {string|null}
 */
function extractExcelBaseName(fileName) {
  // 使用正则表达式找到最后一个点（\.）及之后的所有字符（.*$），并替换为空字符串，从而移除扩展名
  return fileName.replace(/\.([^.]*)$/, "");
}
/**
 * 上传文件事件
 * @param file 文件列表
 * @returns {Promise<void>}
 */
const imageInfo = defineModel("imageInfo", {
  type: Object,
});
const upload = async file => {
  try {
    loadingInstance.value = ElLoading.service({ fullscreen: true, text: "文件上传中，请稍后" });
    const formData = new FormData();
    formData.append("file", file.file);
    const { id, name } = await setImageUpload(formData); //上传文件
    if (imageInfo.value?.hasOwnProperty("backgroundImageId")) {
      const { backgroundImageName, backgroundImageId } = toRefs(imageInfo.value);
      backgroundImageId.value = id;
      backgroundImageName.value = name;
    } else {
      const { imageName, imageId } = toRefs(imageInfo.value);
      imageName.value = name;
      imageId.value = id;
    }
    ElMessage.success("文件上传成功");
  } catch (error) {
    //框架统一对catch里面已做处理 这里无需重复错误提示。
  } finally {
    loadingInstance.value.close();
  }
};
</script>

<style scoped lang="less">
.upload-demo {
  margin-top: 14px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  :deep(.el-upload) {
    --el-upload-dragger-padding-horizontal: 0;
    --el-upload-dragger-padding-vertical: 0;
    .el-upload-dragger {
      width: 134px;
      border: none;
      text-align: start;
      .el-button--primary {
        padding: 8px;
        background: none;
        background: #ffffff;
        border: 1px solid @buttonColor;
        border-radius: 6px;
        span {
          font-size: 18px;
          color: @buttonColor;
          font-weight: 400;
        }
      }
    }
  }
  //上传按钮
  .upload {
    width: 90px;
    height: 38px;
    background: @buttonColor;
    border-radius: 6px;
    border: none;
  }
}
</style>
